// pages/signIn/signIn.js
import { getClockIn, getAddress, clockIn } from '@/api/signInApi'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    clockInAddress: '',
    isAlready: false,
    timer: null,
    nowHour: '--',
    nowMinute: '--',
    obj_id: null,
    isCallClock: null,
    location: '',

    clockInTime: '',
  },

  // 打卡
  submitCheck() {
    if (!this.data.isAlready) {
      console.log('fdsfdsfds');
      const { clockInAddress, location, obj_id, isCallClock } = this.data
      clockIn({ clockInAddress, location, objId: obj_id, isCallClock }).then((res) => {
        console.log(res);
        if (res?.data) {
          const { clockInTime, clockInAddress } = res.data.obj
          wx.showToast({
            title: '打卡成功',
            icon: 'success'
          })
          // clockedInfo: res.data.obj 
          this.setData({ isAlready: true, clockInTime, clockInAddress })
        }
      })
    }
  },

  // 获取时间
  getNowTime() {
    const nowHour = String(new Date().getHours()).padStart(2, "0");
    const nowMinute = String(new Date().getMinutes()).padStart(2, "0");
    this.setData({
      nowHour,
      nowMinute,
    });
    console.log(nowHour, nowMinute);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    const { obj_id, isCallClock, isClock } = options
    this.setData({ obj_id, isCallClock })

    if (isClock == 'N') { // 未打卡
      this.setData({ isAlready: false })
      this.data.timer = setInterval(() => {
        this.getNowTime()
      }, 1000);
      // 获取经纬度 转位置
      wx.getLocation({
        type: 'gcj02',
        success(res) {
          console.log('经纬度', res)
          const lat = res.latitude
          const lon = res.longitude
          let location = `${lon},${lat}`
          that.setData({ location })
          getAddress({ key: "8f9dd0e339538693f067bd1a5ad02b1a", location, extensions: 'all' }).then((res) => {
            console.log(res.regeocode.formatted_address);
            that.setData({ clockInAddress: res.regeocode.formatted_address })
          })
        },
        fail(res) {
          console.log('获取经纬度失败', res)
        }
      })
    } else { // 已打卡
      this.setData({ isAlready: true })
      getClockIn().then((res) => {
        const { clockInAddress, clockInTime } = res.data
        this.setData({ clockInAddress, clockInTime })
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})